<template>
  <div id="app">
    <!--<transition>-->
    <router-view class="child-view"></router-view>
    <!--</transition>-->
  </div>
</template>
<script>
  import MT from './js/mutation-types'
  import './js/url'
  // import VConsole from 'vconsole';

  import utils from './js/utils'
  import { mapState } from 'vuex'
  import QSpinnerOval from 'quasar-framework/src/components/spinner/QSpinnerOval'

  let _self
  let curComponent
  let scanName
  export default {
    name: 'App',
    components: {},
    computed: {
      ...mapState({
        isLoading: state => state.isLoading,
        userCode: state => state.userCode,
      }),
      webHeight () {
        if (window.innerHeight > 1000) {
          return window.innerHeight / 2
        } else {
          return window.innerHeight
        }
      },
      webWidth () {
        return window.screen.width
      }
    },
    data () {
      return {
        transitionName: 'slide-left'
      }
    },
    methods: {
      initAppType () {
        let query = new Url().query
        if (query && query.length) {
          let pam = this.$qs.parse(query.split('?')[1])
          if (pam.appType) {
            this.$store.commit(MT.SET_APP_TYPE, pam.appType)
          }
        }
      },
      init () {
        let path = this.$route.path
        // this.info(url)
        if (path === '/' || path === '' || path === '/#/') {
          this.$router.replace('index')
        } else {
          // this.$router.replace({ name: 'index', params: { redirect: this.$route.path } })
        }
      },
      initFilter () {
        // this.axios.defaults.withCredentials = true
        this.axios.interceptors.request.use(
          config => {
            //this.showLoading()
            if (this.$store.state.token) { // 判断是否存在token，如果存在的话，则每个http header都加上token
              config.headers.Authorization = `token ${this.$store.state.token}`
            }
            if (this.userCode) {
              config.headers.userCode = this.userCode
            }
            return config
          },
          err => {
            this.error('发生错误')
            //this.hideLoading()
            return Promise.reject(err)
          })

        // http response 拦截器

        this.axios.interceptors.response.use(
          response => {
            //this.hideLoading()
            return response
          },
          error => {
            //this.hideLoading()
            if (error && error.response) {
              switch (error.response.status) {
                case 401:
                  // 返回 401 清除token信息并跳转到登录页面
                  this.$store.commit(MT.CLEAR_TOKEN)
                  this.$router.replace({
                    name: 'login',
                    params: { redirect: this.$router.currentRoute.name },
                    query: this.$router.currentRoute.query
                  })
              }
            }
            return Promise.reject(error) // 返回接口返回的错误信息
          })
        this.$router.beforeEach((to, from, next) => {
          this.showLoading()
          if (!to.meta.unRequireAuth) { // 判断该路由是否需要登录权限
            if (this.$store.state.token) { // 通过vuex state获取当前的token是否存在
              next()
            } else {
              next({
                name: 'login',
                params: { redirect: to.name },
                query: to.query // 将跳转的路由path作为参数，登录成功后跳转到该路由
              })
            }
          } else {
            next()
          }
        })
        this.$router.afterEach(to => {
          this.hideLoading()
        })
        this.$router.onError(cb => {
          this.hideLoading()
        })
      },
      setComponent (component, name) {
        _self = this
        curComponent = component
        scanName = name
      },
      toast (value, time, position, color, component) {
        if (time === undefined || time === null) {
          time = 1000
        }
        if (position === undefined || position === null || position === '') {
          position = 'center'
        }

        if (component === undefined || component === null) {
          component = this
        }
        if (color === undefined || color === null) {
          color = 'primary'
        }
        component.$q.notify({ message: value, color: color, timeout: time, position: position })
      },
      info (value, time, position, component) {
        this.toast(value, time, position, 'primary', component)
      },
      tip (value, time, position, component) {
        this.toast(value, time, position, 'secondary', component)
      },
      error (value, time, position, component) {
        this.toast(value, time, position, 'negative', component)
      },
      warn (value, time, position, component) {
        this.toast(value, time, position, 'warning', component)
      },
      confirm (title, text, onConfirm, onCancel) {
        this.$q.dialog({
          title: title,
          message: text,
          ok: '确定',
          cancel: '取消'
        }).then(() => {
          onConfirm()
        }).catch(() => {
          onCancel()
        })
      },
      prompt (title, text, onConfirm, onCancel) {
        this.$q.dialog({
          title: title,
          message: text,
          prompt: {
            model: '',
            type: 'text' // optional
          },
          cancel: true,
          color: 'primary'
        }).then(data => {
          onConfirm(data)
        }).catch(() => {
          onCancel()
        })
      },
      getScanIcon (name, component) {
        let _this = this
        if (window.pda) {
          return [{
            icon: 'crop_free',
            handler () {
              _this.setComponent(component, name)
              try {
                // 安卓交互
                window.pda.scan()
              } catch (e) {
              }
            }
          }]
        } else {
          return []
        }
      },
      scanReturn (data, name) {
        curComponent[name] = data
        let c = curComponent
        curComponent.$nextTick(() => {
          c.$refs[name].$emit('blur')
        })
        this.setComponent(undefined, undefined)
      },
      initEruda () {
        if (process.env.NODE_ENV === 'development' && this.$q.platform.is.mobile) {
          utils.loadJs('//cdn.jsdelivr.net/npm/eruda', () => {
            window.eruda.init()
          })
        }
      },
      initVConsole () {
        /* if (process.env.NODE_ENV === 'development' && this.$q.platform.is.mobile) {
            new VConsole()
          } */
      },
      autoSearch (terms, done) {
        this.axios.post(this.$conf.server + '/autocompleteController/searchList', this.$qs.stringify({ key: terms })).then(res => {
          let data = []
          if (res.data.list) {
            for (let i of res.data.list) {
              data.push({
                value: i.CODE,
                label: i.CODE,
                sublabel: `型号: ${i.CUT_METHOD}`
              })
            }
          }
          done(data)
        })
      },
      showLoading () {
        this.$q.loading.show({
          spinner: QSpinnerOval
        })
      },
      hideLoading () {
        this.$q.loading.hide()
      }
    }, // 监听路由的路径，可以通过不同的路径去选择不同的切换效果
    watch: {
      '$route' (to, from) {
        if (this.$router.isBack) { //  监听路由变化时的状态为前进还是后退
          this.transitionName = 'slide-right'
        } else {
          this.transitionName = 'slide-left'
        }
        this.$router.isBack = false
      }
    },
    created () {
      this.initAppType()
      this.initFilter()
      this.init()
      this.setComponent(this)
      this.initEruda()
      this.initVConsole()
    }
  }
  window.scanReturn = data => {
    _self.scanReturn(data, scanName)
  }
</script>
<style>
  .child-view {
    position: absolute;
    width: 100%;
    transition: all .8s ease;
  }

  .slide-left-enter,
  .slide-right-leave-active {
    opacity: 0;
    -webkit-transform: translate(100%, 0);
    transform: translate(100%, 0);
  }

  .slide-left-leave-active,
  .slide-right-enter {
    opacity: 0;
    -webkit-transform: translate(-100%, 0);
    transform: translate(-100% 0);
  }
</style>
